//
//  TipAbstractListViewController.m
//  TipsProject
//
//  Created by Suny on 15/6/5.
//  Copyright (c) 2015年 Suny. All rights reserved.
//

#import "TipAbstractListViewController.h"

#import "RefreshControl.h"
#define NUMBER_OF_COLUMNS 2
#import "TipsService.h"
#import "TipAbstract.h"
#import "LoadMoreControl.h"
#import "TipInfoDetailViewController.h"
#import "TopicInfo.h"

@interface TipAbstractListViewController()
@property(nonatomic, strong) RefreshControl *refreshControl;
@property(nonatomic, strong) LoadMoreControl *loadMoreControl;

@property (nonatomic, strong)TipsService *tipService;

@property(nonatomic) NSInteger currentPage;

@end
@implementation TipAbstractListViewController

- (TipsService *)tipService
{
	if (!_tipService)
	{
		_tipService = [[TipsService alloc] initDefaultBaseUrlString];
		
	}
	return _tipService;
}


- (RefreshControl *)refreshControl
{
	if (!_refreshControl)
	{
		_refreshControl = [RefreshControl refreshControlWithAttachedView:self.collectionView
																   style:RefreshControlStyleArrow];
		
	}
	return _refreshControl;
	
}

- (LoadMoreControl *)loadMoreControl
{
	if (!_loadMoreControl)
	{
		_loadMoreControl = [[LoadMoreControl alloc] initWithFrame:CGRectMake(0,
																			 0, 
																			 self.collectionView.width,
																			 44) 
													 attachedView:self.collectionView];
		
		[_loadMoreControl addTarget:self
							 action:@selector(triggerLoadMore)
				   forControlEvents:UIControlEventValueChanged];
	}
	
	return _loadMoreControl;
}

- (id)initWithSlideInfo:(id<SlideTabInfoMedol>)slideTabInfo
{
	self = [self init];
	if (self)
	{
		self.slideTabInfo = slideTabInfo;
		
		self.waterfallFlowLayout = [[TipAbstractWaterfallFlowLayout alloc] init];
		// 设置布局的属性
		self.waterfallFlowLayout.columnCount = NUMBER_OF_COLUMNS;
		self.waterfallFlowLayout.sectionInset = UIEdgeInsetsMake(0, 10,10, 10);
		self.waterfallFlowLayout.sectionHeaderHeight = 0;
		
	}
	
	return self;
}


- (void)viewDidLoad 
{
	[super viewDidLoad];
	if (!self.slideTabInfo)
	{
		self.navigationItem.leftBarButtonItem =  self.defaultBackButtonItem;
		[self setNavigationTitle:self.topicInfo.name];

	}
	else
	{
		[self setNavigationTitle:[self.slideTabInfo tabTitle]];

	}
	
	self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 
																			 10 + (self.hasNavigationBar?self.navigationBarHeight:0),
																			 self.view.width, 
																			 self.view.height - (self.hasNavigationBar?self.navigationBarHeight:0) - self.customTabViewController.tabBarHeight)
											collectionViewLayout:self.waterfallFlowLayout];
	self.collectionView.delegate = self;
	self.collectionView.dataSource = self;
	self.collectionView.alwaysBounceVertical = YES;
	
	UIView *backgroundView = [[UIView alloc] initWithFrame:self.collectionView.bounds];
	backgroundView.backgroundColor = [UIColor colorWithHexString:@"dbdbdb"];
	self.view.backgroundColor =  [UIColor colorWithHexString:@"dbdbdb"];
	self.collectionView.backgroundView = backgroundView;
	

	
	[self.collectionView registerClass:[TipAbstractWaterfallFlowCell class] forCellWithReuseIdentifier:@"CellCache"];
	[self.collectionView registerClass:[LNWaterfallFlowFooterView class]
			forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
				   withReuseIdentifier:@"FooterViewCache"];
	self.collectionView.backgroundColor = [UIColor whiteColor];
	[self.view addSubview:self.collectionView];
	
	[WaterFlowDisplayInfo setWidth: (self.collectionView.bounds.size.width - self.waterfallFlowLayout.sectionInset.left - self.waterfallFlowLayout.sectionInset.right)];
	
	[self.refreshControl addTarget:self 
							action:@selector(triggerRefresh) 
				  forControlEvents:UIControlEventValueChanged];


    [self.coverView startAnimating];
	[self triggerRefresh];
}

/**
 *  加载数据
 */
- (void)loadData
{
	self.waterfallFlowLayout.goodsList = self.tipAbstractArray;
//	// 刷新数据
	[self.collectionView reloadData];
}




- (void)viewWillAppear:(BOOL)animated
{
//	if (self.isFirstAppear)
//	{
//		[self.refreshControl beginRefreshing];
//		[self triggerRefresh];
//	}
}

- (void)triggerRefresh
{
	self.currentPage = 0;
	WEAKSELF
    if (self.slideTabInfo)
    {
        [self.tipService getTipsFromServe:self.slideTabInfo.tabId
                           withPageNumber:self.currentPage
                              finishBlock:^(BaseResponse *response) {
                                  STRONGSELF
                                  [strongSelf handleGetTipResponse:response ];

                              }];
    }
    else
    {
        [self.tipService getTipsListWithTopicInfo:_topicInfo
                                       pageNumber:self.currentPage
                                  withFinishBlock:^(BaseResponse *response)
                                  {
                                      STRONGSELF
                                      [strongSelf handleGetTipResponse:response ];

                                  }];
    }

}

- (void)triggerLoadMore
{
	if(self.isHasMore)
	{
		// 如果正在刷新数据，不需要再次刷新
		self.loading = YES;

		self.currentPage ++;
        WEAKSELF

        if (self.slideTabInfo)
        {
            [self.tipService getTipsFromServe:self.slideTabInfo.tabId
                               withPageNumber:self.currentPage
                                  finishBlock:^(BaseResponse *response) {
                                      DLogObject(response);
                                      STRONGSELF
                                      [strongSelf handleGetTipResponse:response ];

                                  }];
        }
        else
        {
            [self.tipService getTipsListWithTopicInfo:_topicInfo
                                           pageNumber:self.currentPage
                                      withFinishBlock:^(BaseResponse *response)
                                      {
                                          STRONGSELF
                                          [strongSelf handleGetTipResponse:response ];

                                      }];
        }

	}
	else
	{
		[self.loadMoreControl removeFromSuperview];
		self.loadMoreControl = nil;
	}

}

- (void)handleGetTipResponse:(BaseResponse *)response
{
	[self.coverView stopAnimating];
	self.coverView.top = - 100;
	[self.refreshControl endRefreshing];
	[self.loadMoreControl endLoading];
	
	
	if (response.httpResponseCode == 200) //网络是否联通
	{
		if (response.success)//服务器是否成功处理
		{
			if (CHECK_VALID_ARRAY(response.object) &&[response.object count] > 0) //数据格式是否正确
			{
				if (self.currentPage == 0)
				{
					[self.tipAbstractArray removeAllObjects];
				}
				[self.tipAbstractArray addObjectsFromArray:response.object];
				
				if ([response.object count] >= kDefaultPageSize)
				{
					self.hasMore = YES;
					[self.footerView addSubview:self.loadMoreControl];
				}
				else 
				{
					self.hasMore = NO;
					[self.loadMoreControl removeFromSuperview];
					self.loadMoreControl = nil;
				}
				[self loadData];

			}
			else
			{
				[self showErrorMessage:Data_Error];
			}
		}
		else
		{
				
			self.currentPage --;
			[self showErrorMessage:response.desc];
		}
		
		
		if ([self.tipAbstractArray count] == 0)
		{
			
			[self.coverView stopAnimationWithRetryAction:@selector(triggerRefresh) withActObject:self];
		}


	}
	else
	{
		[self showErrorMessage:NetWork_NotReachable];
		self.currentPage --;
	}

}

- (void)handleRequestError:(BaseResponse *)response
{

	

}



#pragma mark - 数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	return self.tipAbstractArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	// 创建可重用的cell
	TipAbstractWaterfallFlowCell *cell = [collectionView
								 dequeueReusableCellWithReuseIdentifier:@"CellCache"
								 forIndexPath:indexPath];
	//    cell.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0)
	//                                           green:((float)arc4random_uniform(256) / 255.0)
	//                                            blue:((float)arc4random_uniform(256) / 255.0)
	//                                           alpha:1.0];
	
//	cell.layer.borderWidth = 1;
	
	// background
	cell.backgroundColor = [UIColor whiteColor];
	
	// shadow
	cell.layer.shadowColor = [UIColor colorWithWhite:0.12 alpha:1].CGColor;
	cell.layer.shadowOffset = CGSizeMake(0, 0.5);
	cell.layer.shadowRadius = 1;
	cell.layer.shadowOpacity = 1;
	cell.layer.cornerRadius = 4;
	cell.clipsToBounds = YES;
	cell.good = self.tipAbstractArray[indexPath.item];
	cell.toolBar.toolBarDelegate = self;
	return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
	DLogObject(indexPath);
	
	TipInfoDetailViewController *detailViewController = [[TipInfoDetailViewController alloc] init];
    detailViewController.previewMode = NO;

    TipAbstractWaterfallFlowCell *cell = [collectionView cellForItemAtIndexPath:indexPath];

    TipInfo *tipInfo = [[TipInfo alloc] init];
    tipInfo.tipId = cell.good.abstract.tipId;

    detailViewController.tipInfo = tipInfo;
	
	NavigationController *nav = [AppDelegate rootNavigationController];

    [nav pushViewController:detailViewController
                                         animated:YES];
}

#pragma mark - FooterView
/**
 *  追加视图
 */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView 
		   viewForSupplementaryElementOfKind:(NSString *)kind 
								 atIndexPath:(NSIndexPath *)indexPath 
{
	if (kind == UICollectionElementKindSectionFooter) 
	{

		self.footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind 
															 withReuseIdentifier:@"FooterViewCache" 
																	forIndexPath:indexPath];
		
		if(self.footerView)
		{
			[self.footerView addSubview:_loadMoreControl];
		}
		return self.footerView;
	}
	return nil;
}
//
#pragma mark - scrollView代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	

}


- (BOOL)prefersStatusBarHidden
{
	return YES;
}


- (NSMutableArray *)tipAbstractArray
{
	if (_tipAbstractArray == nil)
    {
		_tipAbstractArray = [NSMutableArray array];
	}
	return _tipAbstractArray;
}






- (void)tipInfoToolBar:(TipInfoToolBar *)toolBar clickView:(TipInfoToolBarItem *)item
{
	WEAKSELF
	if (item.tag == TipInfoToolBarItemTagCommon)
	{
		
	}
	else if (item.tag == TipInfoToolBarItemTagPrise)
	{
		[self.tipService priseTipsToServe:[LoginUserInfo sharedInstance].userId
									tipId:toolBar.abstract.tipId
							  finishBlock:^(BaseResponse *response) {
								  if (response.success)
								  {
									  STRONGSELF
									  [strongSelf showProgressHUDCompleteMessage:@"处理成功！"];
									  item.userInteractionEnabled = NO;
								  }
								  else 
								  {
									  STRONGSELF
									  if ([response.status isEqualToString:@"NotAllowRepeatAction"])
									  {
										  [strongSelf showAlertTip:response.desc];
									  }
									  else
									  {
										  [strongSelf showAlertTip:Data_Error];
									  }
								  } 
							  }];
		
	}
	else if (item.tag == TipInfoToolBarItemTagCollection)
	{
		[self.tipService collectionTipsToServe:[LoginUserInfo sharedInstance].userId
										 tipId:toolBar.abstract.tipId
								   finishBlock:^(BaseResponse *response) {
									   if (response.success)
									   {
										   STRONGSELF
										   [strongSelf showProgressHUDCompleteMessage:@"处理成功！"];
										   item.titleLabel.text = [NSString stringWithFormat:@"%ld",[item.titleLabel.text integerValue]+1];
										   item.userInteractionEnabled = YES;
										   
									   }
									   else 
									   {
										   STRONGSELF
										   if ([response.status isEqualToString:@"NotAllowRepeatAction"])
										   {
											   [strongSelf showAlertTip:response.desc];
										   }
										   else
										   {
											   [strongSelf showAlertTip:Data_Error];
										   }
									   } 
								   }];
	}
	
}
@end
